package com.bs.visitservice.utils;

import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 本地线程工具类
 */
public abstract class ThreadLocalUtil {

    private static final ThreadLocal<Map<Object, Object>> RESOURCES = new ThreadLocal<>();

    public static Map<Object, Object> getResources() {
        return RESOURCES != null ? new HashMap<Object, Object>(RESOURCES.get()) : null;
    }

    public static void setResources(Map<Object, Object> newResources) {
        if (CollectionUtils.isEmpty(newResources)) {
            return;
        }
        RESOURCES.get().clear();
        RESOURCES.get().putAll(newResources);
    }

    private static Object getValue(Object key) {
        return RESOURCES.get().get(key);
    }

    public static Object get(Object key) {
        Object value = getValue(key);
        return value;
    }

    public static Object remove(Object key) {
        Object value = RESOURCES.get().remove(key);

        return value;
    }

    public static void put(Object key, Object value) {
        if (null == value) {
            remove(key);
            return;
        }
        if(RESOURCES.get() == null){
            RESOURCES.set(new HashMap<>());
        }
        RESOURCES.get().put(key, value);
    }

    public static void remove() {
        RESOURCES.remove();
    }
}